package org.douxiaoban.client.activity;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import com.mobclick.android.MobclickAgent;
import org.douxiaoban.client.R;
import org.douxiaoban.client.util.WorkspaceView;
import org.douxiaoban.client.util.WorkspaceView.ScrollToScreenCallback;
import org.douxiaoban.client.adapter.ContactsAdapter;
import org.douxiaoban.client.adapter.MiniBlogAdapter.ClickCallback;
import org.douxiaoban.client.api.DoubanListType;
import org.douxiaoban.client.adapter.MiniBlogAdapter;
import org.douxiaoban.client.api.MiniBlogItemData;
import org.douxiaoban.client.api.MiniBlogList;
import org.douxiaoban.client.api.MiniBlogList.SendType;
import org.douxiaoban.client.api.UserInfoData;
import org.douxiaoban.client.api.UserList;
import org.douxiaoban.client.app.App;
import org.douxiaoban.client.app.Assistant;
import org.douxiaoban.client.util.ThreadTool;
import org.douxiaoban.client.widget.PopupRecommend;
import org.douxiaoban.client.widget.TitleStyle;

import java.util.ArrayList;


public class UserHomeActivity extends BaseActivity
        implements ScrollToScreenCallback, ClickCallback {
	private WorkspaceView scrollView;
	private UserInfoData m_userInfo;
	private Handler mHandler;		
	private UserList mContacts;
//	private UserList mFriends;
	private MiniBlogList mUserMiniBlogs;
	
	private TitleStyle mTitle;
//	private Boolean m_bFirstMiniBlog;
	
	private String mUserId;
	private String mUserName;
	
	private boolean mIsUserInfoFirst;
	private boolean mOnlyContacts;
	
	private PopupRecommend mPopup;
	
	@Override
	public void onCreate(Bundle bundel){
		super.onCreate(bundel);
		initHandler();
		Bundle bundle = getIntent().getExtras();
		mIsUserInfoFirst = true;
//		if(null != bundle){
			mUserId= bundle.getString(Assistant.KEY_USER_ID);
			int index = bundle.getInt(Assistant.KEY_INDEX);
//			App.currentUserName = bundle.getString(Assistant.KEY_USER_NAME);			
//		}
		scrollView = new WorkspaceView(this, null);
		
		mPopup = new PopupRecommend(this);
		
		scrollView.setTouchSlop(32);
		 //scrollView.unlock();	
		LayoutInflater inflater = LayoutInflater.from(this);
	
		View view = inflater.inflate(R.layout.user_info, null);
		ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.FILL_PARENT);
	
				
		View viewListMb = inflater.inflate( R.layout.miniblog_home, null);
		
		MiniBlogAdapter adapterMiniBlog = new MiniBlogAdapter(this);
		ContactsAdapter adapterContacts = new ContactsAdapter(this);
		
		mUserMiniBlogs = new MiniBlogList(this, adapterMiniBlog, DoubanListType.USER_MINIBLOG, viewListMb, mUserId);

		mContacts = new UserList(this, adapterContacts, DoubanListType.CONTACTS);
		//mFriends = new UserList(this, adapterFriends, DoubanListType.FRIENDS);
		adapterMiniBlog.setListView(mUserMiniBlogs.getListView());
		
		initUserList(mContacts);
		
		
		
	    requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
	    setContentView(scrollView);	
	    getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.custom_title);
	    
        mTitle = new TitleStyle(this);
        mTitle.initTitleStyle();
       
        
		//initUserList(mFriends);
		if(Assistant.HOME_INDEX_CONTACTS != index){
			scrollView.addView(View.inflate(this, R.layout.user_info, null));
			scrollView.addView(viewListMb); 	//广播列表
		    initCollectionListent();
			ThreadTool.instace(this).getUserInfo(mUserId, mHandler);
		    mTitle.initPageController(3,1);
		    mTitle.setTitle(getString(R.string.titleUserHome));
		    mOnlyContacts = false;
		}else{
			mOnlyContacts = true;
		    mTitle.initPageController(1,1);
		    mTitle.setTitle(getString(R.string.titleContacts));
			ThreadTool.instace(this).getUserContacts(mUserId, mHandler, 1, App.max);
		}
		scrollView.addView(mContacts.getMainview()); 	//关注列表
		mContacts.getListView().setAdapter(mContacts.getAdapter());
		
		//参数待定...
	
		scrollView.setScrollToScreenCallback(this);



 
        
//        callback(index);
//        scrollView.scrollToScreen(index);
	}
	
	
	private void initHandler(){
		mHandler = new Handler(){
			@Override
			public void handleMessage(Message msg){
				Bundle bundle = msg.getData();
				switch(msg.what){
					case Assistant.TOOLS_MSG_USINFO:
						ThreadTool.UserInfoSerialz serialz =
							(ThreadTool.UserInfoSerialz)bundle.getSerializable(Assistant.TOOLS_KEY_USER_INFO);
					    m_userInfo = serialz.m_userInfo;
					    if(null == m_userInfo){
					    	mPopup.showToastWindow(Assistant.FAIL_POP, "网络异常");
					    }else{
						    updateUserInfo();
					    }
					    break;
					    
					case Assistant.TOOLS_MSG_MINIBLOG:
//						//ui
//						View pb = findViewById(R.id.listProgressBar);
//						pb.setVisibility(View.GONE);
//						m_lvMiniBlog.setVisibility(View.VISIBLE);
//						
//						ThreadTools.MiniBlogSerialz miniblog = 
//							(ThreadTools.MiniBlogSerialz)bundle.getSerializable(Assistant.TOOLS_KEY_MINIBLOG);
//						if(null == miniblog){
//							Toast.makeText(getApplicationContext(), "没有取到数据!!!",
//								     Toast.LENGTH_SHORT).show();
//						}else{
//							
//							m_adapterMiniBlog.addDataTail(miniblog.m_list);
//							m_lvMiniBlog.setAdapter(m_adapterMiniBlog);
////						}
//						m_bFirstMiniBlog = false;
						break;
						
					case Assistant.TOOLS_MSG_CONTACTS:
						ThreadTool.UserInfoListSerialz contactsSer=
							(ThreadTool.UserInfoListSerialz)bundle.getSerializable(Assistant.TOOLS_KEY_CONTACTS);
						if(null == contactsSer.m_list){
							//网络问题!
							mPopup.showToastWindow(Assistant.FAIL_POP, "网络异常");
						}else{
							updateUserList(mContacts, contactsSer.m_list);				
						}
						break;
						
					case Assistant.TOOLS_MSG_FRIENDS:
						ThreadTool.UserInfoListSerialz friendsSer=
							(ThreadTool.UserInfoListSerialz)bundle.getSerializable(Assistant.TOOLS_KEY_FRIENDS);
						if(null == friendsSer.m_list){
							//网络问题!
							mPopup.showToastWindow(Assistant.FAIL_POP, "网络异常");
						}else{
							updateUserList(mContacts, friendsSer.m_list);				
						}
						break;
						
					case Assistant.TOOLS_MSG_AVATAR:
						ThreadTool.ImageSerialz image =
								(ThreadTool.ImageSerialz)bundle.getSerializable(Assistant.TOOLS_KEY_AVATAR);
						ImageView avatar = (ImageView)findViewById(R.id.userInfo_avatar);
						avatar.setImageBitmap(image.m_bitmap);
					default:
						break;
				}
			}
		};
	}
	
	
	private void updateUserInfo(){
		intiUserInfoUi();
	}
	
	private void intiUserInfoUi(){
		//ImageView avatar = (ImageView)findViewById(R.id.userInfo_avatar);
		TextView name = (TextView)findViewById(R.id.userInfo_name);
		//TextView id = (TextView)findViewById(R.id.userInfo_id);
		TextView location = (TextView)findViewById(R.id.userInfo_location);
		TextView summary = (TextView)findViewById(R.id.userInfo_summary);
		TextView signature = (TextView)findViewById(R.id.userInfo_signatrue);
		
		//为了获取头像，（头像使用数字id的组合！）	
//		App.currentUserId = m_userInfo.m_sId;		
		
//		App.currentUserName = m_userInfo.m_sName;
		mUserName = m_userInfo.m_sName;
		name.setText(m_userInfo.m_sName);
		signature.setText(m_userInfo.mSignature);
		//id.setText(m_userInfo.m_sId);
		location.setText(m_userInfo.m_sLocation);
		summary.setText(m_userInfo.m_sSummary);
		//if(null == m_userInfo.m_bmAvatar){
		m_userInfo.m_sImageUrl = m_userInfo.m_sImageUrl.replace("/u", "/ul");
		ThreadTool.instace(this).
				getAvatar(m_userInfo.m_sId, m_userInfo.m_sImageUrl,mHandler, 0);
		//}
	}
	
	
	@Override
	public void callback(int index){
		
		if(mOnlyContacts){
			return;
		}
		mTitle.setCurrentPage(index+1);
		switch(index){
			case Assistant.HOME_INDEX_INFO:
				if(mIsUserInfoFirst){
					ThreadTool.instace(this).getUserInfo(mUserId, mHandler);
				}
				//ThreadTool.instace(this).getUserInfo(App.currentUserId, mHandler);
				mTitle.setTitle(getString(R.string.titleUserHome));
				break;
			case Assistant.HOME_INDEX_MINIBLOG:
				mTitle.setTitle(getString(R.string.titleUserMiniBlog));
				if(mUserMiniBlogs.getIsFirst()){
					//ThreadTools.instace(this).getUserMiniBlog(App.currentUserId, mHandler, 1, App.max);
					mUserMiniBlogs.refeshMiniBlog();
						}
				break;
			case Assistant.HOME_INDEX_CONTACTS:
				mTitle.setTitle(getString(R.string.titleContacts));
				if(mContacts.getIsFirst()){				
					ThreadTool.instace(this).getUserContacts(mUserId, mHandler, 1, App.max);
				}
				break;
			case Assistant.HOME_INDEX_FRIEND:
//				if(mFriends.getIsFirst()){
//					ThreadTool.instace(this).getUserFriends(App.currentUserId, mHandler, 1, App.max);
//				}
				break;
				default:
					break;
		
		}
	}
	
	private  void changeCurrentUser(String userName, String userId){
//		App.currentUserName = userName;
//		App.currentUserId = userId;
		mUserId = userId;
		reset();		
	}
	/**
	 * 监听 豆邮,和收藏
	 */
	private void initCollectionListent(){
		TextView book = (TextView)findViewById(R.id.userInfoBook);
		TextView mail = (TextView)findViewById(R.id.userInfoSendMail);
		TextView movie = (TextView)findViewById(R.id.userInfoMovie);
		TextView music = (TextView)findViewById(R.id.userInfoMusic);
		
		book.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v){
				Intent toBook = new Intent(UserHomeActivity.this, CollectionBookListActivity.class);
				toBook.putExtra(Assistant.KEY_USER_ID, mUserId);
				startActivity(toBook);
			}
		});
		
		mail.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v){
				Intent toSendMail = new Intent(UserHomeActivity.this, SendMailActivity.class);
				toSendMail.putExtra(Assistant.KEY_USER_ID, mUserId);
				toSendMail.putExtra(Assistant.KEY_USER_NAME, mUserName);
				startActivity(toSendMail);
			}
		});
		
		movie.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v){
				Intent toMovie = new Intent(UserHomeActivity.this, CollectionMovieListActivity.class);
				toMovie.putExtra(Assistant.KEY_USER_ID, mUserId);
				startActivity(toMovie);
			}
		});
		
		music.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v){
				Intent toMusic = new Intent(UserHomeActivity.this, CollectionMusicListActivity.class);
				toMusic.putExtra(Assistant.KEY_USER_ID, mUserId);
				startActivity(toMusic);
			}
		});
	}
	/**
	 *  切换用户的时候,重置数据..
	 */
	private void reset(){
		mContacts.reset();
//		mFriends.reset();
//		m_bFirstMiniBlog = true;
		
		((ContactsAdapter)mContacts.getAdapter()).clear();
//		((ContactsAdapter)mFriends.getAdapter()).clear();
		((MiniBlogAdapter)mUserMiniBlogs.getAdapter()).clear();
	}
	
	private void  initUserList(final UserList userList){

		//final MailAdapter adapter = mailList.getAdapter();
		userList.getListView().setOnItemClickListener(new OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int index,
					long id) {	
				UserInfoData data = (UserInfoData)((ContactsAdapter)userList.getAdapter()).getItem(index);
				String userId  = data.m_sId;
//				String userName = data.m_sName;
				//changeCurrentUser(userName, userId);
				Bundle bundel = new Bundle();
				bundel.putString(Assistant.KEY_USER_ID, userId);
				Intent intent = new Intent();
				intent.putExtras(bundel);
				intent.setFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
				intent.setClass(UserHomeActivity.this, UserHomeActivity.class);
				startActivity(intent);
				
				//scrollView.moveToDefaultScreen();
			}
		});
		
		userList.getListView().setOnItemLongClickListener(new OnItemLongClickListener(){	
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				return false;
			}
		});

		userList.getListView().setOnScrollListener(new OnScrollListener(){
			@Override
			public void onScroll(AbsListView v, int firstVisbleItem, int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				if(firstVisbleItem + visibleItemCount == totalItemCount 
						&& (0 != firstVisbleItem)
						&& !userList.getIsUpdateing() 
						&& !userList.getIsEnd()){
					userList.setIsUpdateing(true);
					getMore(userList);
				}
			}

			@Override
			public void onScrollStateChanged(AbsListView arg0, int arg1) {
				// TODO Auto-generated method stub
			}
			
		});
	}
	
	private void getMore(UserList userList){
		userList.setIsUpdateing(true);
		int start = userList.getAdapter().getCount();
		if(DoubanListType.CONTACTS == userList.getType()){
			ThreadTool.instace(this).getUserContacts(mUserId,
													  mHandler, 
													  start +1,
													  App.max);
		}else if(DoubanListType.FRIENDS == userList.getType()){
			ThreadTool.instace(this).getUserFriends(mUserId,
													 mHandler, 
													 start +1,
													 App.max);
		}
	}
	
	private void updateUserList(UserList userList, ArrayList<UserInfoData> dataList){
		userList.getProgressBar().setVisibility(View.GONE);
		userList.getListView().setVisibility(View.VISIBLE);
		((ContactsAdapter)userList.getAdapter()).appendData(dataList);
		if(dataList.size() < App.mMailMax){
			userList.setIsEnd(true);
		}
	//	userList.setMoreCount(userList.getMoreCount() + 1);
		userList.setIsUpdateing(false);
		userList.setIsFirst(false);
	}

	@Override
	public void revBtnClick(String title, SendType type, String str) {
		// TODO Auto-generated method stub
		mUserMiniBlogs.revBtnClick(title, type, str);
	}

	@Override
	public void itemClick(MiniBlogItemData data) {
		mUserMiniBlogs.clickEvent(data);
	}
	@Override
	public void avatarClick(String userName, String userId) {
		// TODO Auto-generated method stub


	}

      @Override
    protected void onResume() {
        MobclickAgent.onResume(this);
        super.onResume();    //Super Method super.onResume();
    }

    @Override
    protected void onPause() {
        MobclickAgent.onPause(this);
        super.onPause();    //Super Method super.onPause();
    }



}